#include <tsin/input/KeyboardInput.hpp>

#include <tsin/input/InputEvent.hpp>
#include <tsin/util/Logger.hpp>

#include <cstring>

#include <SDL/SDL.h>

using namespace tsin;

KeyboardInput::KeyboardInput()
        : defaultEventHandled(0)
{
}

void KeyboardInput::prepareEvent()
{
        defaultEventHandled = 0;
}

bool KeyboardInput::pollEvent(InputEvent &event)
{
        memset(&event, 0, sizeof(InputEvent));

        switch (defaultEventHandled) {
        case 0: /* Movements */
        {
                event.type = INPUT_EVENT_PLAYER_MOVEMENT;
                Uint8 *keystates = SDL_GetKeyState(NULL);
                if (keystates[SDLK_UP])
                        event.data.movement.y ++;
                if (keystates[SDLK_DOWN])
                        event.data.movement.y --;
                if (keystates[SDLK_LEFT])
                        event.data.movement.x --;
                if (keystates[SDLK_RIGHT])
                        event.data.movement.x ++;
                if (keystates[SDLK_LSHIFT])
                        event.data.movement.slow = 1;
                else
                        event.data.movement.slow = 0;
                defaultEventHandled ++;
                return true;
        }
        default: /* polling events from SDL */
                SDL_Event sdlEvent;
                while (SDL_PollEvent(&sdlEvent)) {
                        switch (sdlEvent.type) {
                        case SDL_QUIT:
                                event.type = INPUT_EVENT_GAME_CTRL;
                                event.data.gameControl.event = GAME_CTRL_EXIT;
                                return true;
                        }
                }
        }

        return false;
}
